//
//  HomeViewController.m
//  eticket
//
//  Created by AnhQuocNguyen on 4/8/13.
//  Copyright (c) 2013 SoinMedia. All rights reserved.
//

#import "HomeViewController.h"

 
@interface HomeViewController ()


@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [_parentView setBackgroundColor:[UIColor clearColor]];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (![Utilities isConnectionAvailable]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Network is not connection !!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Try again", nil];
        [alert show];
        SAFE_RELEASE_OBJECT(alert);
    }
    else{
        _isSelectedButtonBack = NO;
        
        //Setup UI & homeview
        [self setupUI];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}





#pragma mark - UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 2000) {
        [_homeView refreshToServer];
    }
    else if(alertView.tag == 12345){
        if (buttonIndex == 1) {
            NSUserDefaults *loginUserDefault = [NSUserDefaults standardUserDefaults];
            [loginUserDefault removeObjectForKey:LOGINED];
            [loginUserDefault removeObjectForKey:Login_name];
            [loginUserDefault removeObjectForKey:access_token_eTicket_userDefault];
            
            if ([arrayMenu count] > 0 ) {
                [arrayMenu removeAllObjects];
            }
            
            [arrayMenu addObject:@"LOGIN"];
            [arrayMenu addObject:@"HOME"];
            [arrayMenu addObject:@"FIND EVENTS"];
            [arrayMenu addObject:@"CATEGORY"];
            [arrayMenu addObject:@"REGISTER/LOGOUT"];
            [arrayMenu addObject:@"CHANGE PASSWORD"];
            
            [_tblViewMenu reloadData];
            
            ////////////////////////////////////////
            //cho dislay registerView
            if (!_registerView) {
                [self setupRegisterView];
            }
            
            _registerView.hidden = NO;
            _categoryEventView.hidden = YES;
            _homeView.hidden = YES;
            _findEventView.hidden = YES;
            _loginView.hidden = YES;
            _changePassView.hidden = YES;
            [self animationForBackView];
        }
    }
    else{
        if (![Utilities isConnectionAvailable]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Network is not connection !!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Try again", nil];
            [alert show];
            SAFE_RELEASE_OBJECT(alert);
        }
        else{
            _isSelectedButtonBack = NO;
            [self setupUI];
        }
    }
}

#pragma mark - 
- (void)animationForBackView{
    if (_isSelectedButtonBack) {
        _isSelectedButtonBack = !_isSelectedButtonBack;
        [_homeView enableButtonSlider:YES];
        [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            CGRect _parentViewFrame = _parentView.frame;
            _parentViewFrame.origin.x = 0;
            _parentView.frame = _parentViewFrame;
        } completion:^(BOOL finished) {
            _btnBack.userInteractionEnabled = YES;
        }];
    }
}

////////////////////////////////////////////////////////////////////////////////
#pragma mark - setupUI
- (void)setupUI{
    
    //FakeView
    _fackeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, [Utilities isDeviceFourInches] ? 50 : 50)];
    _fackeView.alpha = 0.1;
    [_fackeView setBackgroundColor:[UIColor blackColor]];
    [_parentView addSubview:_fackeView];
    
    //////////////////////////////////////////////////////////////////////////
    //init tableView
    arrayMenu = [[NSMutableArray alloc] init];
    
    NSUserDefaults *loginUserDefault = [NSUserDefaults standardUserDefaults];
    if ([loginUserDefault objectForKey:LOGINED] && [[loginUserDefault objectForKey:LOGINED] isEqualToString:@"YES"] && [loginUserDefault objectForKey:access_token_eTicket_userDefault] && ![[loginUserDefault objectForKey:access_token_eTicket_userDefault] isEqualToString:@""]) {
        [arrayMenu addObject:[NSString stringWithFormat:@"Welcome: %@",[loginUserDefault objectForKey:Login_name]]];
    }
    else{
        [arrayMenu addObject:@"LOGIN"];
    }

    
    [arrayMenu addObject:@"HOME"];
    [arrayMenu addObject:@"FIND EVENTS"];
    [arrayMenu addObject:@"CATEGORY"];
    [arrayMenu addObject:@"REGISTER/LOGOUT"];
    [arrayMenu addObject:@"CHANGE PASSWORD"];
    _tblViewMenu.delegate = self;
    _tblViewMenu.dataSource = self;
    
    
    //////////////////////////////////////////////////////////////////////////
    //button back
    _btnBack.exclusiveTouch = YES;
    
    
    //////////////////////////////////////////////////////////////////////////
    //Background
    _imgViewBackground.image = [UIImage imageNamed:[Utilities isDeviceFourInches] ? @"bgHome2.png" : @"bgHome1.png"];
    _imgViewMenuBackground.image = [UIImage imageNamed:[Utilities isDeviceFourInches] ? @"bgMenu2.png" : @"bgMenu1.png"];
    
    //////////////////////////////////////////////////////////////////////////
    //HomeView
    POOL_START
    NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"HomeView" owner:self options:nil];
    _homeView = (HomeView *)[nibArray objectAtIndex:0];
    _homeView.frame = CGRectMake(0, [Utilities isDeviceFourInches] ? 38 : 43, 320, [UIScreen mainScreen].bounds.size.height - 43);
    [_homeView setupUIforHomeView];
    _homeView.HomeViewDelegate = self;
    [_parentView addSubview:_homeView];
    [_parentView setBackgroundColor:[UIColor clearColor]];
    POOL_END
}
#pragma mark - HomeViewDelegate
- (void)homeViewReloadData{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Time out" message:@"Refesh !!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    alert.tag = 2000;
    [alert show];
    SAFE_RELEASE_OBJECT(alert);
}
- (void)homeViewDidSlectedGetTicket:(HomeView *)homeView{
    [UIView animateWithDuration:0.1 animations:^{
        _fackeView.alpha = 0.1;
    }];
}
- (void)homeViewBackFromEventDetailView:(HomeView *)homeView{
    [UIView animateWithDuration:0.1 animations:^{
        _fackeView.alpha = 0.0;
    }];
}
- (void)homeViewDidFinishDowloadData:(HomeView *)homeView{
    [UIView animateWithDuration:0.1 animations:^{
        _fackeView.alpha = 0;
    }];
}



////////////////////////////////////////////////////////////////////////////////
#pragma mark - setupFindEventView & Delegate
- (void)setupFindEventView{
    POOL_START
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FindEventView" owner:self options:nil];
    _findEventView = (FindEventView *)[nib objectAtIndex:0];
    _findEventView.frame = CGRectMake(0, [Utilities isDeviceFourInches] ? 38 : 43, 320, [UIScreen mainScreen].bounds.size.height - 43);
    _findEventView.hidden = YES;
    _findEventView.findEventViewDelegate = self;
    [_findEventView setupUI];
    [_parentView addSubview:_findEventView];
    POOL_END
}
- (void)findEventView:(FindEventView *)findEventView tapButtonSearch:(FinalFindEventView *)finalFindEventView{
    [UIView animateWithDuration:0.1 animations:^{
        _fackeView.alpha = 0.1;
    }];
}
- (void)findEventView:(FindEventView *)findEventView backFromFinalFindEventView:(FinalFindEventView *)finalFindEventView{
    [UIView animateWithDuration:0.1 animations:^{
        _fackeView.alpha = 0;
    }];
}
- (void)findEventViewLoadingFail:(FindEventView *)findEventView{
    if (_findEventView) {
        SAFE_RELEASE_VIEW(_findEventView);
    }
    _homeView.hidden = NO;
    _findEventView.hidden = YES;
    _categoryEventView.hidden = YES;
    _registerView.hidden = YES;
    _loginView.hidden = YES;
    _changePassView.hidden = YES;
    [self animationForBackView];
}
- (void)findEventViewClickMyTicket:(FindEventView *)findEventView{
    [self setupMyTicketView];
    if (_myTicketView) {
        _myTicketView.fromView = @"FindEventView";
        [_myTicketView setupMyticket];
        [_myTicketView getMyTicKetFromServer];
        _categoryEventView.hidden = YES;
        _findEventView.hidden = YES;
        _myTicketView.hidden = NO;
    }
}

////////////////////////////////////////////////////////////////////////////////
#pragma mark - setupCategoryEventView & Delegate
- (void)setupCategoryEventView{
    POOL_START
    NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"CategoryEventView" owner:self options:nil];;
    _categoryEventView = (CategoryEventView *)[nibArray objectAtIndex:0];
    _categoryEventView.frame = CGRectMake(0, [Utilities isDeviceFourInches] ? 38 : 43, 320, [UIScreen mainScreen].bounds.size.height - 43);
    _categoryEventView.hidden = YES;
    _categoryEventView.categoryEventViewDelegate = self;
    [_categoryEventView reloadData];
    [_parentView addSubview:_categoryEventView];
    POOL_END
}
- (void)categoryEventView:(CategoryEventView *)categoryEventView didSelected:(CategoryEvent *)categoryEvent{
    [UIView animateWithDuration:0.1 animations:^{
         _fackeView.alpha = 0.1;
    }];
}
- (void)categoryEventView:(CategoryEventView *)categoryEventView finalFindEventBack:(FinalFindEventView *)finalFindEvent{
    [UIView animateWithDuration:0.1 animations:^{
        _fackeView.alpha = 0;
    }];
}
- (void)categoryEventViewCancelRefeshData:(CategoryEventView *)categoryEventView{
    if (_categoryEventView) {
        SAFE_RELEASE_VIEW(_categoryEventView);
    }
    _homeView.hidden = NO;
    _findEventView.hidden = YES;
    _categoryEventView.hidden = YES;
    _registerView.hidden = YES;
    _loginView.hidden = YES;
    _changePassView.hidden = YES;
    [self animationForBackView];
}
- (void)categoryEventViewClickMyTicket:(CategoryEventView *)categoryEventView{
    [self setupMyTicketView];
    if (_myTicketView) {
        _myTicketView.fromView = @"CategoryView";
        [_myTicketView setupMyticket];
        [_myTicketView getMyTicKetFromServer];
        _categoryEventView.hidden = YES;
        _findEventView.hidden = YES;
        _myTicketView.hidden = NO;
    }
}

////////////////////////////////////////////////////////////////////////////////
#pragma mark - setupRegisterView
- (void)setupRegisterView{
    POOL_START
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"RegisterView" owner:self options:nil];
    _registerView = (RegisterView *)[nib objectAtIndex:0];
    _registerView.frame = CGRectMake(0, [Utilities isDeviceFourInches] ? 38 : 43, 320, [UIScreen mainScreen].bounds.size.height - 43);
    _registerView.hidden = YES;
    [_registerView setupUI];
    _registerView.registerViewDelegate = self;
    [_parentView addSubview:_registerView];
    POOL_END
}
- (void)registerViewDidSeclectCancelRefesh:(RegisterView *)registerView{
    if (_registerView) {
        SAFE_RELEASE_VIEW(_registerView);
    }
    _homeView.hidden = NO;
    _findEventView.hidden = YES;
    _categoryEventView.hidden = YES;
    _registerView.hidden = YES;
    _loginView.hidden = YES;
    _changePassView.hidden = YES;
    [self animationForBackView];
}


////////////////////////////////////////////////////////////////////////////////
#pragma mark - Setup Myticket View
- (void)setupMyTicketView{
    if (!_myTicketView) {
        POOL_START
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyTicket" owner:self options:nil];
        _myTicketView = (MyTicket *)[nib objectAtIndex:0];
        _myTicketView.frame = CGRectMake(0, [Utilities isDeviceFourInches] ? 38 : 43, 320, [UIScreen mainScreen].bounds.size.height - 43);
        _myTicketView.hidden = YES;
        _myTicketView.myTicKetDelegate = self;
        [_parentView addSubview:_myTicketView];
        POOL_END
    }
}
- (void)myTicKetButtonCategoryClick:(MyTicket *)myticket{
    _categoryEventView.hidden = NO;
    _myTicketView.hidden = YES;
}
- (void)myTicKetButtonFindEventClick:(MyTicket *)myticket{
    _findEventView.hidden = NO;
    _myTicketView.hidden = YES;
}

////////////////////////////////////////////////////////////////////////////////
#pragma mark - setupLoginView & Delegate
- (void)setupLoginView{
    POOL_START
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"LoginView" owner:self options:nil];
    _loginView = (LoginView *)[nib objectAtIndex:0];
    _loginView.frame = CGRectMake(0, [Utilities isDeviceFourInches] ? 38 : 43, 320, [UIScreen mainScreen].bounds.size.height - 43);
    _loginView.hidden = YES;
    _loginView.loginViewDelegate = self;
    [_loginView setupLoginView];
    [_parentView addSubview:_loginView];
    POOL_END
}
- (void)loginView:(LoginView *)loginView didLoginSuccessfull:(NSString *)fullName{
    if ([arrayMenu count] > 0 ) {
        [arrayMenu removeAllObjects];
    }
    
    [arrayMenu addObject:[NSString stringWithFormat:@"Welcome: %@", fullName]];
    [arrayMenu addObject:@"HOME"];
    [arrayMenu addObject:@"FIND EVENTS"];
    [arrayMenu addObject:@"CATEGORY"];
    [arrayMenu addObject:@"REGISTER/LOGOUT"];
    [arrayMenu addObject:@"CHANGE PASSWORD"];
    [_tblViewMenu reloadData];
    
    _loginView.hidden = YES;
    _homeView.hidden = NO;
    _findEventView.hidden = YES;
    _categoryEventView.hidden = YES;
    _registerView.hidden = YES;
    _changePassView.hidden = YES;
    
}
- (void)loginView:(LoginView *)loginView tapForgetPassword:(ForgetView *)forgetView{
     _fackeView.alpha = 0.1;
}
- (void)loginView:(LoginView *)loginView forgetViewBack:(ForgetView *)forgetView{
     _fackeView.alpha = 0;
}

- (BOOL)checkLogin{
    NSUserDefaults *loginUserDefault = [NSUserDefaults standardUserDefaults];
    if ([loginUserDefault objectForKey:LOGINED] && [[loginUserDefault objectForKey:LOGINED] isEqualToString:@"YES"]) {
        return YES;
    }
    return NO;
}



////////////////////////////////////////////////////////////////////////////////
#pragma mark - setupChangePassView & Delegate
- (void)setupChangePassView{
    POOL_START
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ChangePassView" owner:self options:nil];
    _changePassView = (ChangePassView *)[nib objectAtIndex:0];
    _changePassView.frame = CGRectMake(0, [Utilities isDeviceFourInches] ? 38 : 43, 320, [UIScreen mainScreen].bounds.size.height - 43);
    _changePassView.changePassViewDelegate = self;
    _changePassView.hidden = YES;
    [_changePassView setupChangePassView];
    [_parentView addSubview:_changePassView];
    POOL_END
}
- (BOOL)checkAccessToken{
    NSUserDefaults *accToken = [NSUserDefaults standardUserDefaults];
    if ([accToken objectForKey:access_token_eTicket_userDefault] && ![[accToken objectForKey:access_token_eTicket_userDefault] isEqualToString:@""]) {
        return YES;
    }
    return NO;
}

////////////////////////////////////////////////////////////////////////////////
#pragma mark - UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [arrayMenu count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *Cellidentifier = @"MenuViewCell";
    MenuViewCell *cell = (MenuViewCell *)[tableView dequeueReusableCellWithIdentifier:Cellidentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MenuViewCell" owner:self options:nil];
        for (id curr in nib) {
            if ([curr isKindOfClass:[MenuViewCell class]]) {
                cell = (MenuViewCell *)curr;
                cell.exclusiveTouch = YES;
                break;
            }
        }
    }
    
    cell.lbMenu.text = [arrayMenu objectAtIndex:indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:
            if ([self checkLogin]) {
                break;
            }
            if (!_loginView) {
                [self setupLoginView];
            }
            _loginView.hidden = NO;
            _homeView.hidden = YES;
            _findEventView.hidden = YES;
            _categoryEventView.hidden = YES;
            _registerView.hidden = YES;
            _changePassView.hidden = YES;
            [self animationForBackView];
            break;
        case 1:
            if (!_homeView) {
                [self setupUI];
            }
            _homeView.hidden = NO;
            _findEventView.hidden = YES;
            _categoryEventView.hidden = YES;
            _registerView.hidden = YES;
            _loginView.hidden = YES;
            _changePassView.hidden = YES;
            [self animationForBackView];
            break;
        case 2:
            if (!_findEventView) {
                [self setupFindEventView];
            }
            _findEventView.hidden = NO;
            _homeView.hidden = YES;
            _categoryEventView.hidden = YES;
            _registerView.hidden = YES;
            _loginView.hidden = YES;
            _changePassView.hidden = YES;
            _myTicketView.hidden = YES;//Hidden myTicketView truoc
            [self animationForBackView];
            break;
        case 3:
            if (!_categoryEventView) {
                [self setupCategoryEventView];
            }
            _categoryEventView.hidden = NO;
            _homeView.hidden = YES;
            _findEventView.hidden = YES;
            _registerView.hidden = YES;
            _loginView.hidden = YES;
            _changePassView.hidden = YES;
            _myTicketView.hidden = YES;//Hidden myTicketView truoc
            [self animationForBackView];
            break;
        case 4:
            if ([self checkLogin]) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Do you want to Log out ?" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
                alert.tag = 12345;
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
                break;
            }
            if (!_registerView) {
                [self setupRegisterView];
            }
            _registerView.hidden = NO;
            _categoryEventView.hidden = YES;
            _homeView.hidden = YES;
            _findEventView.hidden = YES;
            _loginView.hidden = YES;
            _changePassView.hidden = YES;
            [self animationForBackView];
            break;
        case 5:
            if (![self checkAccessToken]) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You must be to login before change password !!!" message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
                break;
            }
            ////////////////////////////////
            if (!_changePassView) {
                [self setupChangePassView];
            }
            _changePassView.hidden = NO;
            _registerView.hidden = YES;
            _categoryEventView.hidden = YES;
            _homeView.hidden = YES;
            _findEventView.hidden = YES;
            _loginView.hidden = YES;
            [self animationForBackView];
        default:
            break;
    }
}


////////////////////////////////////////////////////////////////////////////////
#pragma mark - btnBack_clicked
- (IBAction)btnBack_clicked:(id)sender{
    ////////////////////////////////////////////////////////////////////////////
    [_homeView enableButtonSlider:!_isSelectedButtonBack ? NO : YES];
    
    if (_findEventView) {
        [_findEventView downKeyboar];
    }
    if (_registerView) {
        [_registerView textFieldResignFirstResponder];
    }
    if (_loginView) {
        [_loginView textFieldResignFirstResponder];
    }
    if (_changePassView) {
        [_changePassView textFieldResignFirstResponder];
    }
    
    ////////////////////////////////////////////////////////////////////////////
    __block UIButton *button = (UIButton *)sender;
    button.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        CGRect _parentViewFrame = _parentView.frame;
         _parentViewFrame.origin.x = !_isSelectedButtonBack ? 240 : 0;
        _parentView.frame = _parentViewFrame;
    } completion:^(BOOL finished) {
        
        button.userInteractionEnabled = YES;
        _isSelectedButtonBack = !_isSelectedButtonBack;
    }];
}


////////////////////////////////////////////////////////////////////////////////



- (void)dealloc {
    
    [_parentView release];
    [_tblViewMenu release];
    [_imgViewBackground release];
    [_btnBack release];
    [_imgViewMenuBackground release];
    
    SAFE_RELEASE_OBJECT(_homeView);
    SAFE_RELEASE_OBJECT(_findEventView);
    SAFE_RELEASE_OBJECT(_categoryEventView);
    SAFE_RELEASE_OBJECT(_registerView);
    SAFE_RELEASE_OBJECT(_loginView);
    SAFE_RELEASE_OBJECT(_fackeView);
    SAFE_RELEASE_OBJECT(arrayMenu);
    SAFE_RELEASE_OBJECT(_fackeView);
    [super dealloc];
}
- (void)viewDidUnload {
    [_parentView release];
    _parentView = nil;
    [_tblViewMenu release];
    _tblViewMenu = nil;
    [_imgViewBackground release];
    _imgViewBackground = nil;
    [_btnBack release];
    _btnBack = nil;
    [_imgViewMenuBackground release];
    _imgViewMenuBackground = nil;
    [super viewDidUnload];
}
@end
